#!/bin/bash

MODULE_HOME=/opt/module/jenkins
if [ ! -d "$MODULE_HOME" ]; then
    mkdir -p $MODULE_HOME
fi
#需要修改下目录权限, 因为当映射本地数据卷时，/home/docker/jenkins目录的拥有者为root用户，而容器中jenkins user的uid为1000
chown -R 1000:1000 $MODULE_HOME

# 启动
docker run -d \
    --privileged=true \
    -v /etc/localtime:/etc/localtime:ro \
    -p 8080:8080 \
    -p 50000:50000 \
    -v /opt/module/jenkins:/var/jenkins_home \
    -v /opt/module/maven/apache-maven-3.6.3:/opt/module/maven/apache-maven-3.6.3 \
    -v /opt/repository/maven:/opt/repository/maven \
    --name jenkins \
    docker.io/jenkins/jenkins
# 查看
docker ps -a | grep jenkins

# 访问：http://$IP:8080
IP=`/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v 172.17.0.1|grep -v 10.0.2.15|grep -v inet6|awk '{print $2}'|tr -d "addr:"`
echo "访问：http://$IP:8080"

# 登录密码
echo "登录密码：docker exec jenkins tail /var/jenkins_home/secrets/initialAdminPassword"
docker exec jenkins tail /var/jenkins_home/secrets/initialAdminPassword
#============== 调用本脚本时可用变量 ==============
#>>> $FILE_PATH 文件绝对路径：/opt/software/apache-maven-3.6.3-bin.zip
#>>> $FILE_EXTENSION 文件后缀：zip
#>>> $File_HOME 软件HOME：/opt/module/maven/apache-maven-3.6.3
#>>> $REPO_PATH 仓库目录：/opt/repository/maven
#===================== 生成SSHKey ==========================
# docker exec -it jenkins /bin/bash
# 进入容器后生成sshkey
# ssh-keygen -t rsa
# 在容器内输入exit离开容器，使用如下命令获取公钥
# tail /var/lib/docker/volumes/jenkins/_data/.ssh/id_rsa.pub
# MAVEN环境变量
docker exec -u root jenkins cat >>/etc/profile<<EOF
# .bashrc
# User specific aliases and functions
alias mvn='/opt/module/maven/apache-maven-3.6.3/bin/mvn'
alias ll='ls -l'
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi
#===== 配置 MAVEN_HOME 环境变量 =====
MAVEN_HOME=/opt/module/maven/apache-maven-3.6.3
PATH=$PATH:/opt/module/maven/apache-maven-3.6.3/bin/
export MAVEN_HOME PATH

EOF
# 刷新
docker exec jenkins /bin/bash -c "source ~/.bashrc"
# mvn 环境变量加不上。直接链接bin下
docker exec -u root jenkins /bin/bash -c "ln -s /opt/module/maven/apache-maven-3.6.3/bin/mvn /bin/"


# 创库目录授权
chown 1000:1000 -R /opt/repository/maven
chmod 766 -R /opt/repository/maven
# ============================== 换国内地址，插件 ============================== 
# (0)界面上操作：Manage Jenkins/Plugin Manager/Available 标签下，执行 Install without restart
# (1)容器内替换国内地址
# cd /var/jenkins_home/updates/
# sed -i 's/http:\/\/updates.jenkins-ci.org\/download/https:\/\/mirrors.tuna.tsinghua.edu.cn\/jenkins/g' default.json && sed -i 's/http:\/\/www.google.com/https:\/\/www.baidu.com/g' default.json
# (2)界面上操作：Manage Jenkins/Plugin Manager/Advanced 标签，拖到最下换国内地址
# https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json
# (1)重启
# http://192.168.56.101:8080/restart

# 插件：chim
# Chinese (Simplified)
# Role-based Authorization Strategy
# Credentials Binding Plugin
# git
# jenkins私钥，gogs 公钥
# ssh-keygen -t rsa
